package com.badlogic.androidgames;

import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.opengl.GLU;
import android.os.Vibrator;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.badlogic.androidgames.Settings.GameDifficult;
import com.badlogic.androidgames.asyncutil.AsyncJSONBroker;
import com.badlogic.androidgames.asyncutil.AsyncJSONBrokerGet;
import com.badlogic.androidgames.asyncutil.AsyncResourceLoading;
import com.badlogic.androidgames.asyncutil.JSONReq;
import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Input.KeyEvent;
import com.badlogic.androidgames.framework.Input.TouchEvent;
import com.badlogic.androidgames.framework.MyLine;
import com.badlogic.androidgames.framework.MyMovableImageTextBox;
import com.badlogic.androidgames.framework.MyMovableLabel;
import com.badlogic.androidgames.framework.gl.Camera2D;
import com.badlogic.androidgames.framework.gl.SpriteBatcher;
import com.badlogic.androidgames.framework.impl.GLGame.GLGameState;
import com.badlogic.androidgames.framework.impl.GLScreen;
import com.badlogic.androidgames.framework.math.OverlapTester;
import com.badlogic.androidgames.framework.math.Vector2;
import com.badlogic.androidgames.levelutil.LevelBuilder;
import com.badlogic.androidgames.levelutil.LevelProcessed;
import com.badlogic.androidgames.util.Result.ResourceType;
import com.badlogic.androidgames.Assets;

public class GameScreen extends GLScreen //implements OnClickListener
{	
    Camera2D guiCam;
    SpriteBatcher batcher;
    Vector2 touchPoint;
    int cont = 0, fps;
    int deskHeight;
    int deskWidth;
    int screenHeight = 800;
    int screenWidth = 480;
    int leftBottomX; 
    int leftBottomY;
    		
    Vector2 overlappedDist = new Vector2(0,0);

    MyMovableLabel labelArr[];
    int labelIndexEdit=-1;
    
    MyMovableImageTextBox tbArr[];
    int imageTextBoxIndexEdit=-1;
    public MyMovableImageTextBox tbToFill;
    int tbToFillIndex;
    
    MyLine line[];
    
    int i;
    int r;
    
    double currentTime;

    TouchEvent event;
    List<TouchEvent> touchEvents;
    List<KeyEvent> keyEvents;
    
    InputMethodManager  m;
    Vibrator v;
    
    Vector2 touchDownPoint = new Vector2();
    double touchDownTime;
    boolean touchDownFlag = false;
    
    //FloatBuffer vertices;
    //ByteBuffer byteBuffer; 
    
    boolean multiTouchDownFlag = false;
    Vector2 multiTouchPos1 = new Vector2();
    Vector2 multiTouchPos2 = new Vector2();
    
    public enum LastTouchOperation {THOUCHDOWN,TOUCHUP,DRAGELEMENT,DRAGCAMERA,PINCH,ZOOM,NOTHING};
    LastTouchOperation lastTouchOperation = LastTouchOperation.NOTHING;
    
    
    //int percCompletation=0;
    //int points=3210;
    //String difficult;
    
    boolean resumeFlag = false; 
    
    float angle;
    
    private int testCompletation()
    {
    	int completeObject = 0;
    	int tot = labelArr.length + tbArr.length;
    	for(int label = 0;label < labelArr.length; label++)
    	{
    		labelArr[label].complete = !labelArr[label].text.isEmpty(); 
    		if(labelArr[label].complete == true)
    			completeObject++;
    	}
    	for(int textImg = 0;textImg < tbArr.length; textImg++)
    	{
    		if(tbArr[textImg].complete == true)
    		{
    			completeObject++;
    			testNewAssociation(tbArr[textImg]);
    		}
    	}
    	
    	double ret = ((((double)completeObject)/((double)tot))*100); 
    	
    	return (int)ret;
    }
    
    private void testNewAssociation(MyMovableImageTextBox current)
    {
		MyLine currentLine;
    	for(Iterator<MyLine> linesIter = current.lines.iterator(); linesIter.hasNext(); )
    	{
    		currentLine = linesIter.next();
    		//if((currentLine.associated == false)&&
    		  // (currentLine.tb1.complete == true)&&
    		   //(currentLine.tb2.complete == true))
        	if((currentLine.associated == false)&&
        	   ((currentLine.label.userCompletation == true)||
        	   (currentLine.tb1.userCompletation == true)||
        	   (currentLine.tb2.userCompletation == true))&&
        	   
        	   (currentLine.label.complete == true)&&
               (currentLine.tb1.complete == true)&&
               (currentLine.tb2.complete == true)
        	   
        	   )
    		{
				//currentLine.associated = true;
 
    			//devo creare la do_association
    			/*final String ass ="do association:\n"+ 
    						  "has_associated: "+glGame.gameUserData.username+"\n"+
    		    			  "subject: "+currentLine.tb1.text.getText()+"\n"+
    		    			  "predicate: "+currentLine.tb2.text.getText()+"\n"+
    		    			  "object: "+currentLine.label.text.getText();
    			
    			glGame.runOnUiThread(new Runnable() 
    			{
                    public void run() 
                    {
                    	Toast.makeText(glGame, ass, Toast.LENGTH_LONG).show();                        
                    }
                });*/
    			
        		
        		glGame.runOnUiThread(new Runnable() {
                    public void run() {
                    	glGame.myDialog.setContentView(R.layout.progress);
                    	TextView t = (TextView)glGame.myDialog.findViewById(R.id.progressMsg);
            			t.setText("Creating association ...");
                		glGame.myDialog.show();                
                    }});
        		
    			//creazione della do_association
    			try {
					String path = "http://lenny.cs.indiana.edu:7489/greatminds/users/do_association";
					HashMap<String, String> params = new HashMap<String, String>();
	
					params.put(new String("has_associated"), glGame.gameUserData.username);
					params.put(new String("subject"), currentLine.tb1.text.getText());
					params.put(new String("object"), currentLine.tb2.text.getText());
					params.put(new String("predicate"), currentLine.label.text.getText());
	
					JSONReq req = new JSONReq();
					req.path = path;
					req.params = params;
	
					AsyncJSONBroker resp = (AsyncJSONBroker) new AsyncJSONBroker(glGame).execute(req);
	
					JSONObject res;
					
					res = resp.get();
					String strRes = res.toString();
					JSONObject j = new JSONObject(strRes);

					glGame.gameUserData.points = j.getJSONObject("results").getInt("total_score");
					
					for(int m = 0;m < j.getJSONObject("results").getJSONArray("scores").length(); m++)
					{
						final String msg2 = j.getJSONObject("results").getJSONArray("scores").getJSONObject(m).getString("message");
						glGame.runOnUiThread(new Runnable() 
						{
		                    public void run() 
		                    {
		                    	Toast.makeText(glGame, msg2, /*msg2.length()*10*/Toast.LENGTH_LONG).show();                        
		                    }
		                });						
					}
					
					currentLine.associated = true;
	    			
				} 
    			catch (Exception e) 
    			{
    				glGame.runOnUiThread(new Runnable() 
					{
	                    public void run() 
	                    {
	                    	Toast.makeText(glGame, "errore di connessione con il server", /*msg2.length()*10*/Toast.LENGTH_LONG).show();                        
	                    }
	                });		
//					e.printStackTrace();
				}
    			
    			
    			
    			//creazione della do_description 2
    			try {
    				String path = "http://lenny.cs.indiana.edu:7489/greatminds/users/do_description";
    				HashMap<String, String> params = new HashMap<String, String>();

    				params.put(new String("has_described_concept"), glGame.gameUserData.username);
    				params.put(new String("description_subject"), currentLine.tb2.text.getText());
    				params.put(new String("described_by"), currentLine.tb2.resource.getUrl().toString());
    				if(currentLine.tb2.resource.getType() == ResourceType.TWITTER)
    					params.put(new String("channel"), "TWITTER");
    				else if(currentLine.tb2.resource.getType() == ResourceType.FLICKR)
    					params.put(new String("channel"), "FLICKR");
    				else if(currentLine.tb2.resource.getType() == ResourceType.YOUTUBE)
    					params.put(new String("channel"), "YOUTUBE");

    				JSONReq req = new JSONReq();
    				req.path = path;
    				req.params = params;

    				AsyncJSONBroker resp = (AsyncJSONBroker) new AsyncJSONBroker(glGame).execute(req);

    				JSONObject res;

    				res = resp.get();
    				String strRes = res.toString();

    				final String msg2 = strRes;//j.getJSONObject("results").getJSONArray("scores").getJSONObject(m).getString("message");
    				glGame.runOnUiThread(new Runnable() 
    				{
    					public void run() 
    					{
    						//Toast.makeText(glGame, msg2, Toast.LENGTH_LONG).show();                        
    					}
    				});						
    			} 
    			catch (Exception e) 
    			{
    				glGame.runOnUiThread(new Runnable() 
					{
	                    public void run() 
	                    {
	                    	Toast.makeText(glGame, "errore di connessione con il server", /*msg2.length()*10*/Toast.LENGTH_LONG).show();                        
	                    }
	                });		
    				e.printStackTrace();
    			}
    			
    			//creazione della do_description 1
    			try {
    				String path = "http://lenny.cs.indiana.edu:7489/greatminds/users/do_description";
    				HashMap<String, String> params = new HashMap<String, String>();

    				params.put(new String("has_described_concept"), glGame.gameUserData.username);
    				params.put(new String("description_subject"), currentLine.tb1.text.getText());
    				params.put(new String("described_by"), currentLine.tb1.resource.getUrl().toString());
    				if(currentLine.tb1.resource.getType() == ResourceType.TWITTER)
    					params.put(new String("channel"), "TWITTER");
    				else if(currentLine.tb1.resource.getType() == ResourceType.FLICKR)
    					params.put(new String("channel"), "FLICKR");
    				else if(currentLine.tb1.resource.getType() == ResourceType.YOUTUBE)
    					params.put(new String("channel"), "YOUTUBE");

    				JSONReq req = new JSONReq();
    				req.path = path;
    				req.params = params;

    				AsyncJSONBroker resp = (AsyncJSONBroker) new AsyncJSONBroker(glGame).execute(req);

    				JSONObject res;

    				res = resp.get();
    				String strRes = res.toString();

    				final String msg2 = strRes;//j.getJSONObject("results").getJSONArray("scores").getJSONObject(m).getString("message");
    				glGame.runOnUiThread(new Runnable() 
    				{
    					public void run() 
    					{
    						//Toast.makeText(glGame, msg2, Toast.LENGTH_LONG).show();                        
    					}
    				});						
    			} 
    			catch (Exception e) 
    			{
    				glGame.runOnUiThread(new Runnable() 
					{
	                    public void run() 
	                    {
	                    	Toast.makeText(glGame, "errore di connessione con il server", /*msg2.length()*10*/Toast.LENGTH_LONG).show();                        
	                    }
	                });		
    				e.printStackTrace();
    			}
    			glGame.runOnUiThread(new Runnable() {
    	            public void run() {
    	            	
    	        		glGame.myDialog.hide();                
    	            }});
    		}			
    	}
    }
    
    private void updateObjectsEnabled()
    {
    	for(int textImg = 0;textImg < tbArr.length; textImg++)
    	{
    		if(tbArr[textImg].complete == true)
    		{
    			for(Iterator<MyLine> linesIter = tbArr[textImg].lines.iterator(); linesIter.hasNext(); )
    			{
    				linesIter.next().label.enabled = true;
    			}
    		}	
    	}
    	for(int label = 0;label < labelArr.length; label++)
    	{ 
    		if(labelArr[label].complete == true)
    		{
    			labelArr[label].line.tb2.enabled = true;
    			
    		}
    	}
    }
    
    
    //costruzione della rete di oggetti che compongono la schermata di gioco
    private void buildNetwork()
    {
    	//int numOfElemInSlices[] =  {1, 3, 4, 5, 3};
    	int numOfElemInSlices[] = null;// =  {1, 1, 2};
    	int numOfSlices = 0;
    	int numOfMovableTextImage = 0;
    	int numOfLabels = 0;
    	int numOfLines = 0;
    	//                  0   1 2 3    4 5 6 7     8 9 10 11 12    13 14 15
    	//int childIndex[] = {0,  0,0,0,   1,2,3,3,    4,5,6, 7, 7,    8, 9, 9};
    	
    	int childIndex[] = null;// = {0,  0,   1,1};
    
		
    	if(Settings.gameDifficult == GameDifficult.Easy)
    	{
    		numOfElemInSlices =  new int[3];
    		numOfElemInSlices[0] = 1;
    		numOfElemInSlices[1] = 1;
    		numOfElemInSlices[2] = 2;
    		childIndex = new int [4];
    		childIndex[0] = 0;
    		childIndex[1] = 0;
    		childIndex[2] = 1;
    		childIndex[3] = 1;
    	}
    	else if(Settings.gameDifficult == GameDifficult.Normal)
    	{
    		numOfElemInSlices =  new int[4];
    		numOfElemInSlices[0] = 1;
    		numOfElemInSlices[1] = 1;
    		numOfElemInSlices[2] = 2;
    		numOfElemInSlices[3] = 2;
    		childIndex = new int [6];
    		childIndex[0] = 0;
    		childIndex[1] = 0;
    		childIndex[2] = 1;
    		childIndex[3] = 1;
    		childIndex[4] = 2;
    		childIndex[5] = 3;
    	}
    	else if(Settings.gameDifficult == GameDifficult.Hard)
    	{
    		numOfElemInSlices =  new int[5];
    		numOfElemInSlices[0] = 1;
    		numOfElemInSlices[1] = 3;
    		numOfElemInSlices[2] = 4;
    		numOfElemInSlices[3] = 5;
    		numOfElemInSlices[4] = 3;
    		childIndex = new int [16];
    		childIndex[0] = 0;
    		childIndex[1] = 0;
    		childIndex[2] = 0;
    		childIndex[3] = 0;
    		childIndex[4] = 1;
    		childIndex[5] = 2;
    		childIndex[6] = 3;
    		childIndex[7] = 3;
    		childIndex[8] = 4;
    		childIndex[9] = 5;
    		childIndex[10] = 6;
    		childIndex[11] = 7;
    		childIndex[12] = 7;
    		childIndex[13] = 8;
    		childIndex[14] = 9;
    		childIndex[15] = 9;
    	}
    	
    	numOfSlices = numOfElemInSlices.length;
    	
    	int stepX = 0;
    	int stepY[] =  new int[numOfSlices];
    	
    	
    	int maxNumOfElemInSlices=0;
    	for(int s = 0;s < numOfSlices; s++)
    	{	
    		if(numOfElemInSlices[s] > maxNumOfElemInSlices)
    			maxNumOfElemInSlices = numOfElemInSlices[s]; 
    			
    	}
    	
    	deskWidth = numOfSlices*700;
    	deskHeight = maxNumOfElemInSlices*530;
    	
    	stepX = deskWidth / (numOfSlices+1); 
    	for(int s = 0;s < numOfSlices; s++)
    	{
    		stepY[s] = deskHeight / (numOfElemInSlices[s]+1);
    		
    		numOfMovableTextImage += numOfElemInSlices[s];
			if(s > 0)
			{
				numOfLabels += numOfElemInSlices[s];
				numOfLines += numOfElemInSlices[s];		
			}
    	}
    	
    	
    	tbArr = new MyMovableImageTextBox[numOfMovableTextImage];
    	labelArr = new MyMovableLabel[numOfLabels];
        line = new MyLine[numOfLines];
    	
        
        int labelIndex = 0;
        int lineIndex = 0;
        int textImageIndex = 0;
    	for(int s = 0;s < numOfSlices; s++)
    	{	
    		for(int e = 0;e < numOfElemInSlices[s]; e++)
    		{
    			tbArr[textImageIndex] = new MyMovableImageTextBox(stepX*(s+1), stepY[s]*(e+1), 200, 268);
    	        
    			tbArr[textImageIndex].enabled = false;
    	        
    			if(s > 0)
    			{
    				
    				line[lineIndex] = new MyLine(tbArr[childIndex[textImageIndex]].position.x,
    											 tbArr[childIndex[textImageIndex]].position.y,
    											 tbArr[textImageIndex].position.x,
    											 tbArr[textImageIndex].position.y);
    				
    			labelArr[labelIndex] = new MyMovableLabel(0, 0, 200, 65, line[lineIndex]);
    			labelArr[labelIndex].labelType = MyMovableLabel.type.ANCORATA;
    				
    			labelArr[labelIndex].enabled = false;
    				
    				
    				
        	        line[lineIndex].label = labelArr[labelIndex];
        	        line[lineIndex].tb1 = tbArr[childIndex[textImageIndex]];
        	        line[lineIndex].tb2 = tbArr[textImageIndex];
        
        	        line[lineIndex].enabled = false;
        	        
        	        tbArr[childIndex[textImageIndex]].lines.add(line[lineIndex]);
        	        tbArr[textImageIndex].lines.add(line[lineIndex]);
        	        
        	        
        	        line[lineIndex].updateLabelPosition(tbArr[childIndex[textImageIndex]].position.x,
        	        									tbArr[childIndex[textImageIndex]].position.y,
        	        									tbArr[textImageIndex].position.x,
        	        									tbArr[textImageIndex].position.y);
        	        
        	        labelIndex++;
        	        lineIndex++;
    			}		
    			textImageIndex++;
    		}
    	}   
    }
    
    
    
    
    
    //costruzione della rete di oggetti che compongono la schermata di gioco
    private void buildNetworkFromJSON()
    {
    	
    	glGame.runOnUiThread(new Runnable() {
            public void run() {
            	glGame.myDialog.setContentView(R.layout.progress);
            	TextView t = (TextView)glGame.myDialog.findViewById(R.id.progressMsg);
    			t.setText("Loading level ...");
        		glGame.myDialog.show();                
            }});
    	
    	//ProgressDialog progressBar = (ProgressDialog)glGame.myDialog.findViewById(R.id.progressBar1); 

    	//.progressBar.setMessage("Loading ...");
    	//glGame.progressBar.show();
    	
    	HashMap<String, String> params = new HashMap<String, String>();
    	//params.put(new String("has_described_concept"), glGame.gameUserData.username);
    	JSONReq req = new JSONReq();
    	req.path = "http://lenny.cs.indiana.edu:7489/greatminds/levels/new";
    	req.params = params;

    	//AsyncJSONBrokerGet resp = (AsyncJSONBrokerGet) new AsyncJSONBrokerGet(glGame).execute(req);

    	JSONObject res;
    	
    	LevelProcessed l = null;

    	int numOfElemInSlices[] = null;// =  {1, 1, 2};
    	int numOfSlices = 0;
    	int numOfMovableTextImage = 0;
    	int numOfLabels = 0;
    	int numOfLines = 0;
    	//                    0   1 2 3    4 5 6 7     8 9 10 11 12    13 14 15
    	//int childIndex[] = {0,  0,0,0,   1,2,3,3,    4,5,6, 7, 7,    8, 9, 9};
    	int childIndex[] = null;// = {0,  0,   1,1};

    	try 
    	{
    		//res = resp.get();
    		//String strRes = res.toString();
    		//System.out.println(strRes);

    		LevelBuilder levelBuilder = new LevelBuilder();
    		JSONObject tmp_level = new JSONObject("{\"root\":\"carnahan\",\"depth\":5,\"difficulty\":3,\"level\":[{\"object\":\"born\",\"subject\":\"carnahan\",\"depth\":0,\"object_description\":\"_R1\",\"predicate\":\"DirectObjectOf\"},{\"subject\":\"carnahan\",\"depth\":0,\"object\":\"member\",\"predicate\":\"_R2\"},{\"subject\":\"member\",\"depth\":1,\"object\":\"_R3\",\"predicate\":\"IsA\"},{\"subject\":\"member\",\"depth\":1,\"object\":\"cane\",\"predicate\":\"IsA\"},{\"subject\":\"_R3\",\"depth\":2,\"object\":\"_R5\",\"predicate\":\"MadeOf\"},{\"object\":\"break\",\"subject\":\"_R3\",\"depth\":2,\"object_description\":\"_R6\",\"predicate\":\"DirectObjectOf\"},{\"subject\":\"break\",\"depth\":3,\"object\":\"glass\",\"predicate\":\"_R7\"},{\"object\":\"bad sprain\",\"subject\":\"break\",\"depth\":3,\"object_description\":\"_R8\",\"predicate\":\"IsA\"},{\"object\":\"see through\",\"subject\":\"glass\",\"depth\":4,\"object_description\":\"_R9\",\"predicate\":\"HasProperty\"},{\"subject\":\"glass\",\"depth\":4,\"object\":\"_R10\",\"predicate\":\"UsedFor\"},{\"subject\":\"born\",\"depth\":1,\"object\":\"dog\",\"predicate\":\"RelatedTo\"},{\"subject\":\"born\",\"depth\":1,\"object\":\"_R12\",\"predicate\":\"IsA\"}]}");

    		l = levelBuilder.getLevel(tmp_level);//res);

    		numOfElemInSlices = l.numOfElemInSlices;
    		numOfSlices = l.numOfSlices;
    		numOfMovableTextImage = 0;//l.numOfMovableTextImage;
    		numOfLabels = 0;//l.numOfLabels;
    		numOfLines = 0;//l.numOfLines;
    		childIndex = l.child;

    	} 
    	catch (Exception e1) {
    		e1.printStackTrace();
    	}

    	numOfSlices = numOfElemInSlices.length;

    	int stepX = 0;
    	int stepY[] =  new int[numOfSlices];


    	int maxNumOfElemInSlices=0;
    	for(int s = 0;s < numOfSlices; s++)
    	{	
    		if(numOfElemInSlices[s] > maxNumOfElemInSlices)
    			maxNumOfElemInSlices = numOfElemInSlices[s]; 

    	}

    	deskWidth = numOfSlices*700;
    	deskHeight = maxNumOfElemInSlices*530;

    	stepX = deskWidth / (numOfSlices+1); 
    	for(int s = 0;s < numOfSlices; s++)
    	{
    		stepY[s] = deskHeight / (numOfElemInSlices[s]+1);

    		numOfMovableTextImage += numOfElemInSlices[s];
    		if(s > 0)
    		{
    			numOfLabels += numOfElemInSlices[s];
    			numOfLines += numOfElemInSlices[s];		
    		}
    	}


    	tbArr = new MyMovableImageTextBox[numOfMovableTextImage];
    	labelArr = new MyMovableLabel[numOfLabels];
    	line = new MyLine[numOfLines];

    	int labelIndex = 0;
    	int lineIndex = 0;
    	int textImageIndex = 0;
    	int cont = 0;
    	for(int s = 0;s < numOfSlices; s++)
    	{	
    		for(int e = 0;e < numOfElemInSlices[s]; e++)
    		{
    			tbArr[textImageIndex] = new MyMovableImageTextBox(stepX*(s+1), stepY[s]*(e+1), 200, 268);

    			tbArr[textImageIndex].enabled = true;
    				
    			String ss;
    			String ssLabel;
				try {
					if(cont == 0)
					{
						ss = l.levelArr.getJSONObject(l.indexInLevelArr[cont]).getString("subject");
						ssLabel = "";
					}
					else
					{
						ss = l.levelArr.getJSONObject(l.indexInLevelArr[cont]).getString("object");
						ssLabel = l.levelArr.getJSONObject(l.indexInLevelArr[cont]).getString("predicate");
					}
				} catch (JSONException e1) {
					ss = "err";
					ssLabel = "err";
				}
				
				if(ss.charAt(0)!='_')
				{
	    			for(int c = 0;c < ss.length(); c++)
	    			{
	    				tbArr[textImageIndex].text.processKeyInput(ss.charAt(c));
	    			}
	    			
	    			try {
	    				URI uri = new URI("http", null, "lenny.cs.indiana.edu", 7489, 
	    						"/greatminds/content/described_by_concept/"+ss, null, null);
	    				String path_ = uri.toString(); 
	    				HashMap<String, String> params_ = new HashMap<String, String>();
	    				params_.put(new String("mode"), "full");
	    				JSONReq req_ = new JSONReq();
	    				req_.path = path_;
	    				req_.params = params_;

	    				AsyncJSONBrokerGet resp_ = (AsyncJSONBrokerGet) new AsyncJSONBrokerGet(glGame).execute(req_);

	    				JSONObject res_;

	    				res_ = resp_.get();
	    				
	    				try
	    				{
	    					String channel = res_.getJSONArray("contents").getJSONObject(0).getString("channel");
	    					String url = res_.getJSONArray("contents").getJSONObject(0).getString("url");
	    					if(channel.compareTo("YOUTUBE") == 0)
		    				{
			    				url = url.substring(url.indexOf('=')+1,url.length());
			    				
			    				AsyncResourceLoading d = (AsyncResourceLoading) new 
			    						AsyncResourceLoading(glGame,url).execute(0);
			    				
			    				d.get();
			    				
			    				tbToFill = tbArr[textImageIndex];
			    				tbToFill.setUrlStr("http://i.ytimg.com/vi/"+d.result[0].getId()+"/default.jpg");
			    				tbToFill.toLoad = false;
			    				tbToFill.resource = d.result[0];
			    				tbToFill.complete = true;
			    				tbToFill.loadImageContent(glGame);
			    				tbToFill = null;
		    				}
	    					else if(channel.compareTo("FLICKR") == 0)
		    				{
	    						url = url.substring(42,url.length()-1);
			    				
			    				AsyncResourceLoading d = (AsyncResourceLoading) new 
			    						AsyncResourceLoading(glGame,url).execute(2);
			    				
			    				d.get();
			    				
			    				tbToFill = tbArr[textImageIndex];
	    						tbToFill.setUrlStr(d.result[0].getUrlImg());
	    						tbToFill.toLoad = false;
	    						tbToFill.resource = d.result[0];
	    						tbToFill.complete = true;
	    						tbToFill.loadImageContent(glGame);
			    				tbToFill = null;
		    				}
	    					else if(channel.compareTo("TWITTER") == 0)
		    				{
	    						url = url.substring(url.length()-18,url.length());
			    				
			    				AsyncResourceLoading d = (AsyncResourceLoading) new 
			    						AsyncResourceLoading(glGame,url).execute(1);
			    				
			    				d.get();
			    				
			    				tbToFill = tbArr[textImageIndex];
			    				tbToFill.textContent = d.result[0].getText();
			    				tbToFill.resource = d.result[0];
			    				tbToFill.complete = true;
			    				tbToFill = null;
		    				}
	    				}
	    				catch(Exception ee)
	    				{
	    					
	    				}
	    				

	    			} catch (Exception e1) {
	    				e1.printStackTrace();
	    			}	    			
				}
				cont++;

    			
    			if(s > 0)
    			{

    				line[lineIndex] = new MyLine(tbArr[childIndex[textImageIndex]].position.x,
    						tbArr[childIndex[textImageIndex]].position.y,
    						tbArr[textImageIndex].position.x,
    						tbArr[textImageIndex].position.y);

    				labelArr[labelIndex] = new MyMovableLabel(0, 0, 200, 65, line[lineIndex]);
    				labelArr[labelIndex].labelType = MyMovableLabel.type.ANCORATA;

    				labelArr[labelIndex].enabled = true;

    				if(ssLabel.charAt(0)!='_')
    				{
    					for(int c = 0;c < ssLabel.length(); c++)
    					{
    						labelArr[labelIndex].text.processKeyInput(ssLabel.charAt(c));
    					}
    				}
    				

    				line[lineIndex].label = labelArr[labelIndex];
    				line[lineIndex].tb1 = tbArr[childIndex[textImageIndex]];
    				line[lineIndex].tb2 = tbArr[textImageIndex];

    				line[lineIndex].enabled = true;

    				tbArr[childIndex[textImageIndex]].lines.add(line[lineIndex]);
    				tbArr[textImageIndex].lines.add(line[lineIndex]);


    				line[lineIndex].updateLabelPosition(tbArr[childIndex[textImageIndex]].position.x,
    						tbArr[childIndex[textImageIndex]].position.y,
    						tbArr[textImageIndex].position.x,
    						tbArr[textImageIndex].position.y);

    				labelIndex++;
    				lineIndex++;
    			}		
    			textImageIndex++;
    		}
    	}   
    	glGame.runOnUiThread(new Runnable() {
            public void run() {
            	
        		glGame.myDialog.hide();                
            }});
    }
    
    public GameScreen(Game game) 
    {
        super(game);
        
        batcher = new SpriteBatcher(glGraphics, 500);
        touchPoint = new Vector2();   
        
    	v = (Vibrator) glGame.getApplicationContext().getSystemService("vibrator");

        m = (InputMethodManager) glGame.getApplicationContext().getSystemService("input_method");
        
        //costruisco la rete di oggetti del gioco
        if(glGame.gameUserData.freeMode == true)
        {
        	buildNetwork();
            //abilito la prima textimage
            tbArr[0].enabled = true;
        }
        else 
        {
        	buildNetworkFromJSON();
        }
        
        //labelArr[0].enabled = true;
        
        
        
        //creo la telecamera posizionata sul primo oggetto dopo aver costruito la rete
        guiCam = new Camera2D(glGraphics, screenWidth, screenHeight, 
        								  tbArr[0].position.x, tbArr[0].position.y);
        
        leftBottomX = deskWidth/2 - screenWidth/2;
        leftBottomY = deskHeight/2 - screenHeight/2;
        
        glGame.gameUserData.difficult = Settings.gameDifficult.toString();
    }       

    
	@Override
    public void update(float deltaTime) 
	{	
		
		
		if(glGame.backPressed == true)
		{
			glGame.backPressed = false;

			glGame.runOnUiThread(new Runnable() {
                public void run() {

                	//Dialog dialog = new Dialog(glGame);
                	glGame.myDialog.setContentView(R.layout.exitdialog);
        			
                	Button buttonYes = (Button)glGame.myDialog.findViewById(R.id.buttonExitYes);
                    buttonYes.setOnClickListener(glGame.myDialogHandler);
                    Button buttonNo = (Button)glGame.myDialog.findViewById(R.id.buttonExitNo);
                    buttonNo.setOnClickListener(glGame.myDialogHandler);                	
                	
                	glGame.myDialog.show();
                    glGame.state = GLGameState.Paused;//.onPause();

        	        //dialog.setCancelable(true);    	
                    
                }});
			
			
			
			//game.setScreen(new MainMenu(game));
		}
		
		glGame.gameUserData.percCompletation = testCompletation();
    	
		//if(glGame.gameUserData.percCompletation>10)
		if(glGame.gameUserData.percCompletation==100)
		{
    		game.setScreen(new EndLevelScreen(game));
    		return;
		}
		
    	updateObjectsEnabled();
        
        touchEvents = game.getInput().getTouchEvents();
        keyEvents = game.getInput().getKeyEvents();
        
        //gestione del touch down prolungato su una label
        for(i = 0;i < labelArr.length; i++)
        {
	        currentTime = System.currentTimeMillis();
	        if((labelArr[i].touchDownFlag == true)&&(currentTime - labelArr[i].touchDownStart)>200)
	        {
	        	labelArr[i].touchDownFlag = false;
	        	labelArr[i].inMovement = false;
	
	            v.vibrate(50);
	            
	            if(labelArr[i].yText < guiCam.position.y)
		        {
	            	guiCam.position.x = labelArr[i].position.x;
		            guiCam.position.y = labelArr[i].position.y+50;
		            guiCam.updateCamPosition();
	            }
	        	m.showSoftInput(glGame.glView, 0);
	        	testUserCompletation();
	        	labelIndexEdit = i;
	        	imageTextBoxIndexEdit = -1;
	        	return;
	        }
        }
        
        //caricamento dell'immagine da inserire nella imagetextbox
        if(tbToFill != null)
        {
        	if(tbToFill.toLoad == true)
        	{
        		tbToFill.toLoad = false;
        		tbToFill.loadImageContent(glGame);
        		tbToFill = null;
        	}
        }
        
        //gestione del touch down prolungato su una textbox        
        for(i = 0;i < tbArr.length; i++)
        {
	        currentTime = System.currentTimeMillis();
	        if((tbArr[i].touchDownFlag == true)&&(currentTime - tbArr[i].touchDownStart)>200)
	        {
	        	tbArr[i].touchDownFlag = false;
	        	tbArr[i].inMovement = false;
	
	            v.vibrate(50);
	            
	            
	        	//m.showSoftInput(glGame.glView, 0);
	        	if(tbArr[i].textTouchDown == false)
	        	{
		            tbToFill = tbArr[i];
		            tbToFillIndex = i;
		        	glGame.runOnUiThread(new Runnable() {
	                    public void run() {

	                    	glGame.myDialog.setContentView(R.layout.ricerca);
	                    	Spinner spinner = (Spinner) glGame.myDialog.findViewById(R.id.spinner1);
	                    	ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(glGame,
	                    	        R.array.sn_array, android.R.layout.simple_spinner_item);
	                    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	                    	spinner.setAdapter(adapter);
	                    	spinner.setOnItemSelectedListener(glGame.myDialogHandler);
	                    	
	                    	EditText editText1;
	            			editText1 = (EditText)glGame.myDialog.findViewById(R.id.editText1);
	            			if(!tbToFill.text.isEmpty())
	            				editText1.setText(tbToFill.text.getText());
	            			
	                    	Button button = (Button)glGame.myDialog.findViewById(R.id.button1);
	                        button.setOnClickListener(glGame.myDialogHandler);
	                    	
	                        glGame.myDialog.show();

	                        glGame.state = GLGameState.Paused;//.onPause();
	                        
	                    }});
	        	}
	        	else
	        	{
	        		if(tbArr[i].yText < guiCam.position.y)
			        {
		            	guiCam.position.x = tbArr[i].position.x;
			            guiCam.position.y = tbArr[i].yText+30;
			            guiCam.updateCamPosition();
		            }
	        		m.showSoftInput(glGame.glView, 0);
	        		testUserCompletation();
	        		imageTextBoxIndexEdit = i;
		        	labelIndexEdit = -1;

	        	}
	        	
	        	return;
	        }
        }
        
        //gestione del spostamento delle label ancorate ad una linea
        /*for(i = 0;i < line.length; i++)
        {
        	line[i].updateLabelPosition(line[i].tb1.position.x,line[i].tb1.position.y,
        								line[i].tb2.position.x,line[i].tb2.position.y);
        }*/
        
        int len = touchEvents.size();
        for(int j = 0; j<len;j++)//if(len == 1)
        {
            event = touchEvents.get(j);  
            //gestione del touch down 
            if(event.type == TouchEvent.TOUCH_DOWN) 
            {
                touchPoint.set(event.x, event.y);
                guiCam.touchToWorld(touchPoint);
  
                lastTouchOperation = LastTouchOperation.THOUCHDOWN;
                
                //gestione del touchdown su una label
                for(i = 0;i < labelArr.length; i++)
                {
	                if((OverlapTester.pointInRectangle(labelArr[i].bounds, touchPoint))&&(labelArr[i].enabled == true) ) 
	                {
	                	currentTime = System.currentTimeMillis();
	                	if(labelArr[i].touchDownFlag == false) {
	                		labelArr[i].touchDownStart = currentTime;
	                		labelArr[i].touchDownFlag = true;
	                    }
	                    
	                	labelArr[i].setTouchDownPosition(touchPoint.x, touchPoint.y);
	                	labelArr[i].inMovement = true;
	                	
	                	touchDownFlag = false;
	                
	                    return;
	                }
                }
                //gestione del touchdown su una textbox
                for(i = 0;i < tbArr.length; i++)
                {
	                if((OverlapTester.pointInRectangle(tbArr[i].bounds, touchPoint))&&(tbArr[i].enabled == true) ) 
	                {
	                	if(touchPoint.y - tbArr[i].bounds.lowerLeft.y<68)
	                		tbArr[i].textTouchDown = true;
	                	else
	                		tbArr[i].textTouchDown = false;
	                		
	                	currentTime = System.currentTimeMillis();
	                	if(tbArr[i].touchDownFlag == false) {
	                		tbArr[i].touchDownStart = currentTime;
	                		//tbArr[i].doubleTouchDownStart = currentTime;
	                		tbArr[i].touchDownFlag = true;
	                		//tbArr[i].doubleTouchDownFlag = true;
	                    }
	                	
//gestione del doppio tocco su una textbox

	                	if(tbArr[i].doubleTouchDownFlag == false) {
	                		tbArr[i].doubleTouchDownStart = currentTime;
	                		tbArr[i].doubleTouchDownFlag = true;
	                    }
	                	else if((tbArr[i].doubleTouchDownFlag == true)&&
	                			((System.currentTimeMillis() - tbArr[i].doubleTouchDownStart)<500))
	                	{
	                		tbArr[i].doubleTouchDownStart = 0.0;
	                		tbArr[i].doubleTouchDownFlag = false;
	                		//touchPoint.set(event.x, event.y);
	                        //guiCam.touchToWorld(touchPoint);
	                        
	                        for(int ii = 0;ii < labelArr.length; ii++)
	                        {
	                        	labelArr[ii].inMovement = false;
	                        	labelArr[ii].touchDownFlag = false;
	                        }
	                        
	                        for(int ii = 0;ii < tbArr.length; ii++)
	                        {
	                        	tbArr[ii].inMovement = false;
	                        	tbArr[ii].touchDownFlag = false;
	                        }
	                		//String url = "https://mobile.twitter.com/NicoSavi/status/227782022058352640";
	                        if(tbArr[i].resource != null)
	                        {
	                        	String url = tbArr[i].resource.getUrl();
	                        	Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));//"vnd.youtube://YoXdA4siPdQ"
	                        	glGame.startActivity(intent);
	                        }
	    				    
	                	}
	                	else if((tbArr[i].doubleTouchDownFlag == true)&&
	                			((System.currentTimeMillis() - tbArr[i].doubleTouchDownStart)>500))
	                	{
	                		tbArr[i].doubleTouchDownStart = currentTime;
	                		tbArr[i].doubleTouchDownFlag = true;
	                    } 
	                	
//fine gestione del doppio tocco su una textbox
	                	
	                	tbArr[i].setTouchDownPosition(touchPoint.x, touchPoint.y);
	                	tbArr[i].inMovement = true;
	                
	                	touchDownFlag = false;
	                	
	                    return;
	                }
                }
                
                //rilevazione del tocco di due dita e attivazione della gestione dello zoom con multitouch
                if(touchDownFlag == true ) 
                {
                	if(event.pointer == 1)
                	{
                		
                		multiTouchPos1.x = touchDownPoint.x;
                		multiTouchPos1.y = touchDownPoint.y;
                		
                		multiTouchPos2.x = touchPoint.x;
                		multiTouchPos2.y = touchPoint.y;
                		
                		multiTouchDownFlag = true;
                		
                		return;
                	}
                }
                
                
                //gestione del doppio tocco su schermo: zoom
                if(touchDownFlag == false ) 
                {
                	touchDownTime = System.currentTimeMillis();
                }
                
            	currentTime = System.currentTimeMillis();
                if(touchDownFlag == true && ((currentTime-touchDownTime) < 500))
                {
                	if(guiCam.zoom < 1.1)
                		guiCam.zoom = 2;
                	else
                		guiCam.zoom = 1;
                	
		            guiCam.updateCamPosition();
                	touchDownFlag = false;
                	return;
                }
                else if(touchDownFlag == true && ((currentTime-touchDownTime) > 500))
                {
                	touchDownTime = System.currentTimeMillis();
                }
                
                touchDownFlag = true;
                touchDownPoint.x = touchPoint.x;
                touchDownPoint.y = touchPoint.y;

            }
            
            //gestione del trascinamento
            if(event.type == TouchEvent.TOUCH_DRAGGED) 
            {
                touchPoint.set(event.x, event.y);
                guiCam.touchToWorld(touchPoint);
                
                
                // gestione dello zoom con il multitouch
                if(multiTouchDownFlag == true)
                {
                	lastTouchOperation = LastTouchOperation.PINCH;
                	
                	double prod =((multiTouchPos1.x-multiTouchPos2.x)*(multiTouchPos1.x-multiTouchPos2.x))+
                				 ((multiTouchPos1.y-multiTouchPos2.y)*(multiTouchPos1.y-multiTouchPos2.y)); 
                 	
                	double distancePos1Pos2 = Math.sqrt(prod);
                	
                	if(event.pointer == 0)
                	{
                		multiTouchPos1.x = touchPoint.x;
                		multiTouchPos1.y = touchPoint.y;
                	}
                	else if(event.pointer == 1)
                	{
                		multiTouchPos2.x = touchPoint.x;
                		multiTouchPos2.y = touchPoint.y;
                	}
                	
                	if(touchEvents.size()>1)
                	{
                		for(int kk = 1;kk < touchEvents.size(); kk++)
                		{
	                		event = touchEvents.get(kk);  
	                		touchPoint.set(event.x, event.y);
	                		guiCam.touchToWorld(touchPoint);
	                     
		                    if(event.pointer == 0)
		                	{
		                		multiTouchPos1.x = touchPoint.x;
		                		multiTouchPos1.y = touchPoint.y;
		                	}
		                	else if(event.pointer == 1)
		                	{
		                		multiTouchPos2.x = touchPoint.x;
		                		multiTouchPos2.y = touchPoint.y;
		                	}
	                    }
                	}
                	
                	double prodPast =((multiTouchPos1.x-multiTouchPos2.x)*(multiTouchPos1.x-multiTouchPos2.x))+
                					 ((multiTouchPos1.y-multiTouchPos2.y)*(multiTouchPos1.y-multiTouchPos2.y)); 
            	
                	double distancePos1Pos2Past = Math.sqrt(prodPast);
                	
                	float diff = (float)(distancePos1Pos2Past - distancePos1Pos2);
                	float incr = 0.003f*diff;
                	
                	
                	if(diff>0)
                	{
                		if(guiCam.zoom>0.8)
                			guiCam.zoom -= incr;
                	}
                	else
                	{
                		if(guiCam.zoom<3.0)
                			guiCam.zoom -= incr;
                	}
                	
                	
                	
                	/*if(distancePos1Pos2 > distancePos1Pos2Past)
                	{
                		if(guiCam.zoom>0.8)
                			guiCam.zoom -= 0.0012f*(distancePos1Pos2 - distancePos1Pos2Past);
                	}
                	else if(distancePos1Pos2 < distancePos1Pos2Past)
                	{
                		if(guiCam.zoom<3.0)
                			guiCam.zoom += 0.0012f*(distancePos1Pos2Past - distancePos1Pos2);
                	}*/
                	
		            guiCam.updateCamPosition();
		            
		            
		            
		            for(int kk = 0;kk < touchEvents.size(); kk++)
            		{
                		event = touchEvents.get(kk);  
                		touchPoint.set(event.x, event.y);
                		guiCam.touchToWorld(touchPoint);
                     
	                    if(event.pointer == 0)
	                	{
	                		multiTouchPos1.x = touchPoint.x;
	                		multiTouchPos1.y = touchPoint.y;
	                	}
	                	else if(event.pointer == 1)
	                	{
	                		multiTouchPos2.x = touchPoint.x;
	                		multiTouchPos2.y = touchPoint.y;
	                	}
                    }
		            
		            return;
                }	
                

                
                touchDownFlag = false;
                
                //trascinamento delle label trascinabili
                for(i = 0;i < labelArr.length; i++)
                {
	                if(labelArr[i].inMovement == true && labelArr[i].labelType == MyMovableLabel.type.TRASCINABILE) 
	                {	
	                	labelArr[i].translateTo(touchPoint.x, labelArr[i].yTouchDown);
	                	labelArr[i].touchDownFlag = false;
	                
	                	for(r = 0;r < tbArr.length;r++)
	                	{
	                		if(OverlapTester.overlapRectanglesOnX(labelArr[i].bounds, tbArr[r].bounds,overlappedDist))
	                		{
	                			labelArr[i].translateAt(labelArr[i].position.x-overlappedDist.x, 
	                									labelArr[i].position.y-overlappedDist.y);
	                			break;
	                		}
	                	}
	                	for(r = 0;r < labelArr.length;r++)
	                	{
	                		if((r != i)&&(OverlapTester.overlapRectanglesOnX(labelArr[i].bounds, labelArr[r].bounds,overlappedDist)))
	                		{
	                			labelArr[i].translateAt(labelArr[i].position.x-overlappedDist.x, 
	                									labelArr[i].position.y-overlappedDist.y);
	                			break;
	                		}
	                	}
	                	
	                	labelArr[i].translateTo(labelArr[i].xTouchDown, touchPoint.y);
	                	labelArr[i].touchDownFlag = false;
	                
	                	for(r = 0;r < tbArr.length;r++)
	                	{
	                		if(OverlapTester.overlapRectanglesOnY(labelArr[i].bounds, tbArr[r].bounds,overlappedDist))
	                		{
	                			labelArr[i].translateAt(labelArr[i].position.x-overlappedDist.x, 
    													labelArr[i].position.y-overlappedDist.y);
	                			break;
	                		}
	                	}
	                	for(r = 0;r < labelArr.length;r++)
	                	{
	                		if((r != i)&&(OverlapTester.overlapRectanglesOnY(labelArr[i].bounds, labelArr[r].bounds,overlappedDist)))
	                		{
	                			labelArr[i].translateAt(labelArr[i].position.x-overlappedDist.x, 
    													labelArr[i].position.y-overlappedDist.y);
	                			break;
	                		}
	                	}
	                		
	                    return;
	                }
	                if(labelArr[i].inMovement == true && labelArr[i].labelType != MyMovableLabel.type.TRASCINABILE) {
	                
	                	labelArr[i].touchDownFlag = false;
	                		
	                    return;
	                }
                }
                //trascinamento delle textimage 
                for(i = 0;i < tbArr.length; i++)
                {
	                if(tbArr[i].inMovement == true) 
	                {	
	                	tbArr[i].translateTo(touchPoint.x, tbArr[i].yTouchDown);
	                	tbArr[i].touchDownFlag = false;
	                
	                	for(r = 0;r < tbArr.length;r++)
	                	{
	                		if((r != i)&&(OverlapTester.overlapRectanglesOnX(tbArr[i].bounds, tbArr[r].bounds,overlappedDist)))
	                		{
	                			tbArr[i].translateAt(tbArr[i].position.x-overlappedDist.x, 
	                								 tbArr[i].position.y-overlappedDist.y);
	                			break;
	                		}
	                	}
	                	for(r = 0;r < labelArr.length;r++)
	                	{
	                		if(OverlapTester.overlapRectanglesOnX(tbArr[i].bounds, labelArr[r].bounds,overlappedDist))
	                		{
	                			tbArr[i].translateAt(tbArr[i].position.x-overlappedDist.x, 
       								 				 tbArr[i].position.y-overlappedDist.y);
	                			break;
	                		}
	                	}
	                	
	                	tbArr[i].translateTo(tbArr[i].xTouchDown, touchPoint.y);
	                	tbArr[i].touchDownFlag = false;
	                
	                	for(r = 0;r < tbArr.length;r++)
	                	{
	                		if((r != i)&&(OverlapTester.overlapRectanglesOnY(tbArr[i].bounds, tbArr[r].bounds,overlappedDist)))
	                		{
	                			tbArr[i].translateAt(tbArr[i].position.x-overlappedDist.x, 
							 				 		 tbArr[i].position.y-overlappedDist.y);
	                			break;
	                		}
	                	}
	                	for(r = 0;r < labelArr.length;r++)
	                	{
	                		if(OverlapTester.overlapRectanglesOnY(tbArr[i].bounds, labelArr[r].bounds,overlappedDist))
	                		{
	                			tbArr[i].translateAt(tbArr[i].position.x-overlappedDist.x, 
							 				 		 tbArr[i].position.y-overlappedDist.y);
	                			break;
	                		}
	                	}
	                	//aggiornamento delle linee collegate alla textimage, vanno cosi ad aggiornare la 
	                	//posizione della label collegata---- spostato da sopra
	                	//non gestita la collisione delle label in questo caso
	                	for(int li = 0;li < tbArr[i].lines.size(); li++)
            			{
            				MyLine lineToUpdate = tbArr[i].lines.get(li);
            				lineToUpdate.updateLabelPosition(lineToUpdate.tb1.position.x,lineToUpdate.tb1.position.y,
            						lineToUpdate.tb2.position.x,lineToUpdate.tb2.position.y);	
            			}
	                	
	                    return;
	                }
                }
                
                if(lastTouchOperation != LastTouchOperation.TOUCHUP)
                {
	                //gestione del trascinamento della telecamera
	                guiCam.position.x = (guiCam.position.x - touchPoint.x) + touchDownPoint.x;
	                guiCam.position.y = (guiCam.position.y - touchPoint.y) + touchDownPoint.y;
	                
	                
	                if(guiCam.position.x > (deskWidth - screenWidth/2))
	                	guiCam.position.x = deskWidth - screenWidth/2;
	                else if(guiCam.position.x < screenWidth/2)
	                	guiCam.position.x = screenWidth/2;
	                
	                if(guiCam.position.y > (deskHeight - screenHeight/2))
	                	guiCam.position.y = deskHeight - screenHeight/2;
	                else if(guiCam.position.y < screenHeight/2)
	                	guiCam.position.y = screenHeight/2;
	                
	                guiCam.updateCamPosition();
	                
	                touchPoint.set(event.x, event.y);
	                guiCam.touchToWorld(touchPoint);
	                touchDownPoint.x = touchPoint.x;
	                touchDownPoint.y = touchPoint.y;
                }
            }
            
            //gestione del touch up
            if(event.type == TouchEvent.TOUCH_UP) 
            {
                touchPoint.set(event.x, event.y);
                guiCam.touchToWorld(touchPoint);
                
                lastTouchOperation = LastTouchOperation.TOUCHUP;
                
                for(i = 0;i < labelArr.length; i++)
                {
                	labelArr[i].inMovement = false;
                	labelArr[i].touchDownFlag = false;
                }
                
                for(i = 0;i < tbArr.length; i++)
                {
                	tbArr[i].inMovement = false;
                	tbArr[i].touchDownFlag = false;
                }
                
                if(multiTouchDownFlag == true)
                {
                	multiTouchDownFlag = false;
                	//touchDownPoint.x = 0.00f;
                	//touchDownPoint.y = 0.00f;
                    //touchDownFlag = false;

                }
            }
        }
        
        
        leftBottomX = (int)(guiCam.position.x) - screenWidth/2;
        leftBottomY = (int)(guiCam.position.y) - screenHeight/2;
        
        //gestione dei tasti premuti
        len = keyEvents.size();
        for(i = 0; i < len; i++) 
        {
            KeyEvent event = keyEvents.get(i);
            
            if(event.type == KeyEvent.KEY_DOWN) {
                
            }
            
            if(event.type == KeyEvent.KEY_UP) 
            {
            	if(Integer.valueOf(event.keyChar)==10)
            	{
            		testUserCompletation();
            		imageTextBoxIndexEdit = -1;
            		labelIndexEdit = -1;
                    m.hideSoftInputFromWindow(glGame.glView.getWindowToken(), 0);
            	}
            	else
            	{
            		if(labelIndexEdit!=-1)
            		{
            			labelArr[labelIndexEdit].text.processKeyInput(event.keyChar);
            			labelArr[labelIndexEdit].edited = true;
            		}
            		if(imageTextBoxIndexEdit!=-1)
            		{
            			tbArr[imageTextBoxIndexEdit].text.processKeyInput(event.keyChar);
            			tbArr[imageTextBoxIndexEdit].edited = true;
            		}
            	}
            }
        }
    }

	void testUserCompletation()
	{
		if(labelIndexEdit != -1)
		{
			if(labelArr[labelIndexEdit].edited == true)
			{
	    		if(labelArr[labelIndexEdit].text.isEmpty())
					labelArr[labelIndexEdit].userCompletation = false;
				else
					labelArr[labelIndexEdit].userCompletation = true;
	    		labelArr[labelIndexEdit].edited = false;
			}
		}
		if(imageTextBoxIndexEdit != -1)
		{
			if(tbArr[imageTextBoxIndexEdit].edited == true)
			{
	    		if(tbArr[imageTextBoxIndexEdit].text.isEmpty())
					tbArr[imageTextBoxIndexEdit].userCompletation = false;
				else if(tbArr[imageTextBoxIndexEdit].resource != null)
					tbArr[imageTextBoxIndexEdit].userCompletation = true;
	    		tbArr[imageTextBoxIndexEdit].edited = false;
			}
		}
	}
	
	
    @Override
    public void present(float deltaTime) {
        GL10 gl = glGraphics.getGL();        
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        guiCam.setViewportAndMatrices();
        
        gl.glEnable(GL10.GL_TEXTURE_2D);
        
        gl.glEnable(GL10.GL_BLEND);
        gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
        
        //bg
        batcher.beginBatch(Assets.backgroundGS);
        	batcher.drawSprite(deskWidth/2, deskHeight/2, deskWidth, deskHeight, Assets.backgroundRegionGS);
        batcher.endBatch();
        
        //linee
        
        for(i = 0;i < line.length; i++)
        {
        	if((line[i].tb1.enabled == false)||(line[i].tb2.enabled == false))
        	{
		      	gl.glColor4f(1.0f, 1.0f, 1.0f, 0.05f);
	        	batcher.beginBatch(Assets.myLine);      
	       			batcher.drawMyLine(line[i].tb1.position.x, line[i].tb1.position.y, line[i].tb2.position.x, line[i].tb2.position.y, Assets.line);
	       		batcher.endBatch();
	       		gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
        	}
        	if((line[i].tb1.enabled == true)&&(line[i].label.enabled == true))
        	{
	        	batcher.beginBatch(Assets.myLine);      
	       			batcher.drawMyLine(line[i].tb1.position.x, line[i].tb1.position.y, line[i].label.position.x, line[i].label.position.y, Assets.line);
	       		batcher.endBatch();
        	}
        	if((line[i].tb2.enabled == true)&&(line[i].label.enabled == true))
        	{
	        	batcher.beginBatch(Assets.myLine);      
	       			batcher.drawMyLine(line[i].tb2.position.x, line[i].tb2.position.y, line[i].label.position.x, line[i].label.position.y, Assets.line);
	       		batcher.endBatch();
        	}
        }
                               
        
        //label
              
	    for(i = 0;i < labelArr.length; i++)
	    {
	    	if(labelArr[i].enabled == false)
	      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
	    	batcher.beginBatch(Assets.myButton);
	      		batcher.drawSprite(labelArr[i].position.x, labelArr[i].position.y, labelArr[i].width, labelArr[i].height, Assets.button);
	      	batcher.endBatch();
	      	gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	    }
        
        
        //freccie
        for(i = 0;i < line.length; i++)
        {
            angle = (float)Math.atan2((line[i].tb1.position.y-line[i].tb2.position.y), (line[i].tb1.position.x-line[i].tb2.position.x)) * Vector2.TO_DEGREES;
            if(angle < 0)
                angle += 360;
	        //left
	    	if((angle >0.00) && (angle < 45))
	    	{
		    	if(labelArr[i].enabled == false)
		      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
	    		batcher.beginBatch(Assets.myLeftArrow);
	       			batcher.drawSprite(labelArr[i].position.x, labelArr[i].position.y+60, 44,44, Assets.leftArrow);
	       		batcher.endBatch();
	       		gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	    	}
	    	else if((angle >=315.00) && (angle < 360))
	    	{
	    		if(labelArr[i].enabled == false)
		      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
	    		batcher.beginBatch(Assets.myLeftArrow);
	       			batcher.drawSprite(labelArr[i].position.x, labelArr[i].position.y+60, 44,44, Assets.leftArrow);
	       		batcher.endBatch();
	       		gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	    	}
	    	//down
	    	else if((angle >=45.00) && (angle <135))
	    	{
	    		if(labelArr[i].enabled == false)
		      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
	    		batcher.beginBatch(Assets.myDownArrow);
	   				batcher.drawSprite(labelArr[i].position.x, labelArr[i].position.y+60, 44,44, Assets.downArrow);
	   			batcher.endBatch();
	   			gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	    	}
	    	//right
	    	else if((angle >=135.00) && (angle <225))
	    	{
	    		if(labelArr[i].enabled == false)
		      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
	    		batcher.beginBatch(Assets.myRightArrow);
	       			batcher.drawSprite(labelArr[i].position.x, labelArr[i].position.y+60, 44,44, Assets.rightArrow);
	       		batcher.endBatch();
	       		gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	    	}
	    	//up
	    	else if((angle >=225.00) && (angle <315))
	    	{
	    		if(labelArr[i].enabled == false)
		      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
	    		batcher.beginBatch(Assets.myUpArrow);
	       			batcher.drawSprite(labelArr[i].position.x, labelArr[i].position.y+60, 44,44, Assets.upArrow);
	       		batcher.endBatch();
	       		gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	    	}
        	
        	//batcher.beginBatch(Assets.fontTexture);
	    		//Assets.font.drawText(batcher, String.valueOf(angle), labelArr[i].position.x, labelArr[i].position.y+110);
	    	//batcher.endBatch();
        }

        //imageTextBox
        
           
	    for(i = 0;i < tbArr.length; i++)
	    {
	      	if(tbArr[i].enabled == false)
	      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
	       	batcher.beginBatch(Assets.myImageTextBox);   
	       		batcher.drawSprite(tbArr[i].position.x, tbArr[i].position.y, tbArr[i].width, tbArr[i].height, Assets.imageTextBox);
	       	batcher.endBatch();
	       	gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);    	
	    }
        
	    
        //contenuto delle imageTextBox piu' loghi delle risorse
        for(int i = 0;i < tbArr.length; i++)
        {
    		if(tbArr[i].regionContent != null)
    		{
    			/*tbArr[i].ratio = (tbArr[i].width-20) / tbArr[i].regionContentWidth;
    			tbArr[i].h = tbArr[i].regionContentHeight * tbArr[i].ratio;
    			tbArr[i].w = (tbArr[i].width-20);
    			if(tbArr[i].h > 180)
    			{

    				tbArr[i].w = 180 * tbArr[i].w / tbArr[i].h;
    				tbArr[i].h = 180;    				
    			}*/
    			
    			
    			tbArr[i].h = 182;//tbArr[i].regionContentHeight;
    			tbArr[i].w = 182;//tbArr[i].regionContentWidth;
    			    			
    			if(tbArr[i].enabled == false)
    	      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
				batcher.beginBatch(tbArr[i].textureContent);      
	        		batcher.drawSprite(tbArr[i].position.x, tbArr[i].position.y+34, 
	        			tbArr[i].w, tbArr[i].h, tbArr[i].regionContent);
	        	batcher.endBatch();
	        	gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	        	if(tbArr[i].resource.getType() == ResourceType.YOUTUBE)
	        	{
	        		if(tbArr[i].enabled == false)
	    	      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
					batcher.beginBatch(Assets.myYtLogo);      
		        	batcher.drawSprite(tbArr[i].position.x+62, tbArr[i].position.y-29, 
		        			50,50, Assets.ytLogo);
		        	batcher.endBatch();
		        	gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	        	}
	        	else if(tbArr[i].resource.getType() == ResourceType.FLICKR)
	        	{
	        		if(tbArr[i].enabled == false)
	    	      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
					batcher.beginBatch(Assets.myFlLogo);      
		        	batcher.drawSprite(tbArr[i].position.x+62, tbArr[i].position.y-29, 
		        			50,50, Assets.flLogo);
		        	batcher.endBatch();	        		
		        	gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	        	}
    		}
    		else if(tbArr[i].textContent != null)
    		{
    			gl.glEnable(GL10.GL_BLEND);
    	        gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
        		if(tbArr[i].enabled == false)
    	      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);    	        
    			batcher.beginBatch(Assets.fontTextureBlack);
    	        	Assets.font.drawMultiLineText(batcher, tbArr[i].textContent, tbArr[i].xText+15, tbArr[i].position.y+115, 15);
    	        batcher.endBatch();
    	        gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    	        
    	        if(tbArr[i].resource.getType() == ResourceType.TWITTER)
	        	{
    	        	if(tbArr[i].enabled == false)
        	      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
					batcher.beginBatch(Assets.myTwLogo);      
		        		batcher.drawSprite(tbArr[i].position.x+62, tbArr[i].position.y-29, 
		        			50,50, Assets.twLogo);
		        	batcher.endBatch();
		        	gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	        	}
    		}
        }
        
        gl.glEnable(GL10.GL_BLEND);
        gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
        //texto nelle label
    	
	    for(i = 0;i < labelArr.length; i++)
	    {
	    	if(labelArr[i].enabled == false)
	      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
	    	batcher.beginBatch(Assets.fontTextureBlack);
	    		Assets.font.drawMultiLineText(batcher, labelArr[i].text.getText(), labelArr[i].xText, labelArr[i].yText, 19);
	    	batcher.endBatch();
	    	gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	    }
	    
	    //testo nelle imageTextBox
	    
	    for(int i = 0;i < tbArr.length; i++)
	    {
	    	if(tbArr[i].enabled == false)
	      		gl.glColor4f(1.0f, 1.0f, 1.0f, 0.3f);
	    	batcher.beginBatch(Assets.fontTexture);
	    		Assets.font.drawMultiLineText(batcher, tbArr[i].text.getText(), tbArr[i].xText, tbArr[i].yText,19);
	    	batcher.endBatch();
	    	gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	    }
        
        
        //passo in 2d
        gl.glDisable( GL10.GL_CULL_FACE );
        gl.glDisable( GL10.GL_DEPTH_TEST );

        gl.glMatrixMode( GL10.GL_PROJECTION );
        gl.glLoadIdentity();
        GLU.gluOrtho2D( gl, (int)(guiCam.position.x)-screenWidth/2, (int)(guiCam.position.x)+screenWidth/2, 
        		(int)(guiCam.position.y)-screenHeight/2, (int)(guiCam.position.y)+screenHeight/2);

        gl.glMatrixMode( GL10.GL_MODELVIEW );
        gl.glLoadIdentity();
        
        
        //hud bg
        batcher.beginBatch(Assets.hud);      
        	batcher.drawSprite(leftBottomX+screenWidth/2 , leftBottomY+screenHeight-20, 
        					   screenWidth, 40, 
        					   Assets.hudBG);
        batcher.endBatch();

        
    
        
        //barra della percentuale di completamento
        /*float h = 36*glGame.gameUserData.percCompletation / 100;
        batcher.beginBatch(Assets.hudPerc);      
    	batcher.drawSprite(leftBottomX+20 , leftBottomY+screenHeight-38+h/2, 
    					   20, h, 
    					   Assets.hudPercBG);
    	batcher.endBatch();
        */
        
        if(cont == 60)
        {
        	cont = 0;
        	fps = (int)(1/deltaTime);
        }
        else 
        	cont++;
        
        batcher.beginBatch(Assets.brainTexture);
        //for(int uu=0;uu<11;uu++)
        //{
        
        int index = glGame.gameUserData.percCompletation*10/100;
        //leftBottomX+20 , leftBottomY+screenHeight-38+h/2
    	batcher.drawSprite(leftBottomX+30 , leftBottomY+screenHeight-20, 
    					   50, 30, 
    					   Assets.brain[index]);
        //}
    	batcher.endBatch();
        
        batcher.beginBatch(Assets.fontTexture);
        	
        	Assets.font.drawText(batcher, "multitouch:", leftBottomX+10, leftBottomY+160);
        	Assets.font.drawText(batcher, "pos1y="+(int)multiTouchPos1.y, leftBottomX+10, leftBottomY+145);
	    	Assets.font.drawText(batcher, "pos1x="+(int)multiTouchPos1.x, leftBottomX+10, leftBottomY+130);
	    	Assets.font.drawText(batcher, "pos2y="+(int)multiTouchPos2.y, leftBottomX+10, leftBottomY+115);
	    	Assets.font.drawText(batcher, "pos2x="+(int)multiTouchPos2.x, leftBottomX+10, leftBottomY+100);
	    	
	    	Assets.font.drawText(batcher, "zoom="+guiCam.zoom, leftBottomX+10, leftBottomY+55);
	        Assets.font.drawText(batcher, "tx="+touchPoint.x, leftBottomX+10, leftBottomY+40);
	        Assets.font.drawText(batcher, "ty="+touchPoint.y, leftBottomX+10, leftBottomY+25);
	        Assets.font.drawText(batcher, String.valueOf(fps), leftBottomX+10, leftBottomY+10);
	        
	        //Assets.font.drawText(batcher, "   "+glGame.gameUserData.percCompletation+"%    P.:"+glGame.gameUserData.points
				//	+"   Diff:"+glGame.gameUserData.difficult, leftBottomX+5, leftBottomY+screenHeight-20);
	        Assets.font.drawText(batcher, glGame.gameUserData.percCompletation+"%", leftBottomX+70, leftBottomY+screenHeight-20);
	        Assets.font.drawText(batcher, "Punti:"+glGame.gameUserData.points, leftBottomX+300, leftBottomY+screenHeight-20);
	        //Assets.font.drawText(batcher, "Diff:"+glGame.gameUserData.difficult, leftBottomX+300, leftBottomY+screenHeight-20);

        batcher.endBatch();
        
        gl.glDisable(GL10.GL_TEXTURE_2D);
        gl.glDisable(GL10.GL_BLEND);

        //da cambiare, perche rimane la schermata nera quando rientro dalla visualizzazione 
    	//su browser dei contenuti. Per il resto funziona, ma dovrei far fare prima un ciclo
    	//che aggiorni lo schermo
        /*if(resumeFlag == true)
    	{
    		resumeFlag = false;

            glGame.state = GLGameState.Paused;//.onPause();    	
            
    	}*/
        
    }
    
    @Override
    public void pause() {        
        Settings.save(game.getFileIO());
    }

    @Override
    public void resume() {
    	for(int k = 0;k < tbArr.length;k ++)
    	{
	    	if(tbArr[k].regionContent != null)
			{
				if(tbArr[k].textureContent!=null)
					tbArr[k].reloadImageContent(glGame);
			}
    	}
    	/*if(glGame.myDialog.isShowing())
    	{
            glGame.state = GLGameState.Running;

    		resumeFlag = true;
    	}*/
    }       

    @Override
    public void dispose() {        
    }
    
    
    
/*    @Override
	public void onClick(View v) {

		
		if(v.getId() == R.id.buttonExitNo)
		{
			glGame.myDialog.hideAndResume();
		}
		else if(v.getId() == R.id.buttonExitYes)
		{
			game.setScreen(new MainMenu(game));
			
		}
		
		
	}
  */  
    
}
